package ling.learn.antlr.delphi;

import java.io.IOException;
import java.nio.charset.Charset;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import ling.learn.antlr.common.AstDumper;
import ling.learn.antlr.delphi.gen.DelphiLexer;
import ling.learn.antlr.delphi.gen.DelphiParser;

public class DelphiAnalyzer {

  public void execute(String resourcePath) throws IOException {
    ParseTree tree = parser(resourcePath);
    dump(resourcePath + ".ast", tree);
    tracer(tree);
  }

  private ParseTree parser(String resourcePath) throws IOException {
    CharStream input = CharStreams.fromFileName(resourcePath, Charset.forName("MS932"));
    DelphiLexer lexer = new DelphiLexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    DelphiParser parser = new DelphiParser(tokens);
    ParseTree tree = parser.file();
    return tree;
  }

  private void tracer(ParseTree tree) {
    DelphiTracer visitor = new DelphiTracer();
    visitor.visit(tree);
  }

  private void dump(String viewPath, ParseTree tree) throws IOException {
    AstDumper view = new AstDumper();
    view.dump(viewPath, tree, DelphiParser.VOCABULARY, false);
  }

}
